package com.leyantech.ecp.agenx.common.di;

import com.leyantech.utility.config.ConfigUtil;

import com.ctrip.framework.apollo.ConfigService;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.JWTOptions;
import io.vertx.ext.auth.PubSecKeyOptions;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.JWTAuthOptions;
import io.vertx.ext.web.handler.JWTAuthHandler;
import lombok.Getter;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-21.
 */
@Singleton
public class JWTAuthProvider implements Provider<JWTAuth> {

  private final Supplier<JWTAuth> jwtAuthSupplier;

  @Getter
  private volatile JWTAuthHandler jwtAuthHandler;

  @Inject
  public JWTAuthProvider(Vertx vertx) {
    final String secret = ConfigService.getAppConfig().getProperty("jwt.secret", "");

    final JWTAuthOptions defaultJwtAuthOptions = new JWTAuthOptions()
        .addPubSecKey(new PubSecKeyOptions().setAlgorithm("HS256").setBuffer(secret))
        .setJWTOptions(new JWTOptions().setExpiresInSeconds((int) TimeUnit.DAYS.toSeconds(7L)));

    this.jwtAuthSupplier = ConfigUtil.getDynamicConfig(
        "jwt.options",
        json -> {
          final JWTAuth jwtAuth = JWTAuth.create(vertx, new JWTAuthOptions(new JsonObject(json)));
          this.jwtAuthHandler = JWTAuthHandler.create(jwtAuth);
          return jwtAuth;
        },
        JWTAuth.create(vertx, defaultJwtAuthOptions)
    );

    this.jwtAuthHandler = JWTAuthHandler.create(jwtAuthSupplier.get());
  }

  @Override
  public JWTAuth get() {
    return jwtAuthSupplier.get();
  }

}
